<template>
  <div ref="chart" style="width: 100%; height: 100%" />
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'AreaChart',
  props: {
    chartData: {
      type: Object,
      required: true
    },
    yAxisName: {
      type: String,
      default: ''
    },
    color: {
      type: String,
      default: '#1890ff'
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler() {
        this.initChart()
      }
    }
  },
  mounted() {
    this.initChart()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    if (this.chart) {
      this.chart.dispose()
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart)
      const option = {
        grid: {
          top: 20,
          right: 10,
          bottom: 20,
          left: 40
        },
        xAxis: {
          type: 'category',
          data: this.chartData.xData,
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#fff'
          }
        },
        yAxis: {
          type: 'value',
          name: this.yAxisName,
          nameTextStyle: {
            padding: [0, 0, 0, 30],
            color: '#fff'
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#fff'
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: 'rgba(255, 255, 255, 0.2)'
            }
          }
        },
        legend: {
          data: [this.yAxisName],
          textStyle: {
            color: '#fff'
          },
          // 添加以下配置确保图例标志颜色与系列一致
          itemStyle: {
            color: this.color
          }
        },
        series: [
          {
            name: this.yAxisName,
            data: this.chartData.yData,
            type: 'line',
            smooth: true,
            symbol: 'none',
            lineStyle: {
              color: this.color,
              width: 2
            },
            itemStyle: {
              // 添加此项确保tooltip指示点颜色一致
              color: this.color
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: `${this.color}80`
                },
                {
                  offset: 1,
                  color: `${this.color}10`
                }
              ])
            }
          }
        ],
        tooltip: {
          trigger: 'axis',
          textStyle: {
            color: '#fff' // 文字颜色
          }
        }
      }
      this.chart.setOption(option)
    },
    handleResize() {
      this.chart && this.chart.resize()
    }
  }
}
</script>
